<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Writing your first Django app, part 1 &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../index.html" />
    <link rel="up" title="Getting started" href="index.html" />
    <link rel="next" title="Writing your first Django app, part 2" href="tutorial02.html" />
    <link rel="prev" title="Quick install guide" href="install.html" />



 
<script type="text/javascript" src="../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="install.html" title="Quick install guide">previous</a>
     |
    <a href="index.html" title="Getting started" accesskey="U">up</a>
   |
    <a href="tutorial02.html" title="Writing your first Django app, part 2">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="intro-tutorial01">
            
  <div class="section" id="s-writing-your-first-django-app-part-1">
<span id="writing-your-first-django-app-part-1"></span><h1>Writing your first Django app, part 1<a class="headerlink" href="#writing-your-first-django-app-part-1" title="Permalink to this headline">¶</a></h1>
<p>Let&#8217;s learn by example.</p>
<p>Throughout this tutorial, we&#8217;ll walk you through the creation of a basic
poll application.</p>
<p>It&#8217;ll consist of two parts:</p>
<ul class="simple">
<li>A public site that lets people view polls and vote in them.</li>
<li>An admin site that lets you add, change and delete polls.</li>
</ul>
<p>We&#8217;ll assume you have <a class="reference internal" href="install.html"><em>Django installed</em></a> already. You can
tell Django is installed and which version by running the following command:</p>
<div class="highlight-console"><div class="highlight"><pre><span class="gp">$</span> python -c <span class="s2">&quot;import django; print(django.get_version())&quot;</span>
</pre></div>
</div>
<p>If Django is installed, you should see the version of your installation. If it
isn&#8217;t, you&#8217;ll get an error telling &#8220;No module named django&#8221;.</p>
<p>This tutorial is written for Django 1.7 and Python 3.2 or later. If the
Django version doesn&#8217;t match, you can refer to the tutorial for your version
of Django by using the version switcher at the bottom right corner of this
page, or update Django to the newest version. If you are still using Python
2.7, you will need to adjust the code samples slightly, as described in
comments.</p>
<p>See <a class="reference internal" href="../topics/install.html"><em>How to install Django</em></a> for advice on how to remove
older versions of Django and install a newer one.</p>
<div class="admonition-where-to-get-help admonition">
<p class="first admonition-title">Where to get help:</p>
<p class="last">If you&#8217;re having trouble going through this tutorial, please post a message
to <a class="reference internal" href="../internals/mailing-lists.html#django-users-mailing-list"><em>django-users</em></a> or drop by <a class="reference external" href="irc://irc.freenode.net/django">#django on irc.freenode.net</a> to chat with other Django users who might
be able to help.</p>
</div>
<div class="section" id="s-creating-a-project">
<span id="creating-a-project"></span><h2>Creating a project<a class="headerlink" href="#creating-a-project" title="Permalink to this headline">¶</a></h2>
<p>If this is your first time using Django, you&#8217;ll have to take care of some
initial setup. Namely, you&#8217;ll need to auto-generate some code that establishes a
Django <a class="reference internal" href="../glossary.html#term-project"><em class="xref std std-term">project</em></a> &#8211; a collection of settings for an instance of Django,
including database configuration, Django-specific options and
application-specific settings.</p>
<p>From the command line, <tt class="docutils literal"><span class="pre">cd</span></tt> into a directory where you&#8217;d like to store your
code, then run the following command:</p>
<div class="highlight-console"><div class="highlight"><pre><span class="gp">$</span> django-admin.py startproject mysite
</pre></div>
</div>
<p>This will create a <tt class="docutils literal"><span class="pre">mysite</span></tt> directory in your current directory. If it didn&#8217;t
work, see <a class="reference internal" href="../faq/troubleshooting.html#troubleshooting-django-admin-py"><em>Problems running django-admin.py</em></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">You&#8217;ll need to avoid naming projects after built-in Python or Django
components. In particular, this means you should avoid using names like
<tt class="docutils literal"><span class="pre">django</span></tt> (which will conflict with Django itself) or <tt class="docutils literal"><span class="pre">test</span></tt> (which
conflicts with a built-in Python package).</p>
</div>
<div class="admonition-where-should-this-code-live admonition">
<p class="first admonition-title">Where should this code live?</p>
<p>If your background is in plain old PHP (with no use of modern frameworks),
you&#8217;re probably used to putting code under the Web server&#8217;s document root
(in a place such as <tt class="docutils literal"><span class="pre">/var/www</span></tt>). With Django, you don&#8217;t do that. It&#8217;s
not a good idea to put any of this Python code within your Web server&#8217;s
document root, because it risks the possibility that people may be able
to view your code over the Web. That&#8217;s not good for security.</p>
<p class="last">Put your code in some directory <strong>outside</strong> of the document root, such as
<tt class="file docutils literal"><span class="pre">/home/mycode</span></tt>.</p>
</div>
<p>Let&#8217;s look at what <a class="reference internal" href="../ref/django-admin.html#django-admin-startproject"><tt class="xref std std-djadmin docutils literal"><span class="pre">startproject</span></tt></a> created:</p>
<div class="highlight-python"><div class="highlight"><pre>mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py
</pre></div>
</div>
<div class="admonition-doesn-t-match-what-you-see admonition">
<p class="first admonition-title">Doesn&#8217;t match what you see?</p>
<p class="last">The default project layout recently changed. If you&#8217;re seeing a &#8220;flat&#8221;
layout (with no inner <tt class="file docutils literal"><span class="pre">mysite/</span></tt> directory), you&#8217;re probably using
a version of Django that doesn&#8217;t match this tutorial version.  You&#8217;ll
want to either switch to the older tutorial or the newer Django version.</p>
</div>
<p>These files are:</p>
<ul class="simple">
<li>The outer <tt class="file docutils literal"><span class="pre">mysite/</span></tt> root directory is just a container for your
project. Its name doesn&#8217;t matter to Django; you can rename it to anything
you like.</li>
<li><tt class="file docutils literal"><span class="pre">manage.py</span></tt>: A command-line utility that lets you interact with this
Django project in various ways. You can read all the details about
<tt class="file docutils literal"><span class="pre">manage.py</span></tt> in <a class="reference internal" href="../ref/django-admin.html"><em>django-admin.py and manage.py</em></a>.</li>
<li>The inner <tt class="file docutils literal"><span class="pre">mysite/</span></tt> directory is the actual Python package for your
project. Its name is the Python package name you&#8217;ll need to use to import
anything inside it (e.g. <tt class="docutils literal"><span class="pre">mysite.urls</span></tt>).</li>
<li><tt class="file docutils literal"><span class="pre">mysite/__init__.py</span></tt>: An empty file that tells Python that this
directory should be considered a Python package. (Read <a class="reference external" href="http://docs.python.org/tutorial/modules.html#packages">more about
packages</a> in the official Python docs if you&#8217;re a Python beginner.)</li>
<li><tt class="file docutils literal"><span class="pre">mysite/settings.py</span></tt>: Settings/configuration for this Django
project.  <a class="reference internal" href="../topics/settings.html"><em>Django settings</em></a> will tell you all about how settings
work.</li>
<li><tt class="file docutils literal"><span class="pre">mysite/urls.py</span></tt>: The URL declarations for this Django project; a
&#8220;table of contents&#8221; of your Django-powered site. You can read more about
URLs in <a class="reference internal" href="../topics/http/urls.html"><em>URL dispatcher</em></a>.</li>
<li><tt class="file docutils literal"><span class="pre">mysite/wsgi.py</span></tt>: An entry-point for WSGI-compatible web servers to
serve your project. See <a class="reference internal" href="../howto/deployment/wsgi/index.html"><em>How to deploy with WSGI</em></a> for more details.</li>
</ul>
<div class="section" id="s-database-setup">
<span id="database-setup"></span><h3>Database setup<a class="headerlink" href="#database-setup" title="Permalink to this headline">¶</a></h3>
<p>Now, edit <tt class="file docutils literal"><span class="pre">mysite/settings.py</span></tt>. It&#8217;s a normal Python module with
module-level variables representing Django settings.</p>
<p>By default, the configuration uses SQLite. If you&#8217;re new to databases, or
you&#8217;re just interested in trying Django, this is the easiest choice. SQLite is
included in Python, so you won&#8217;t need to install anything else to support your
database. When starting your first real project, however, you may want to use a
more robust database like PostgreSQL, to avoid database-switching headaches
down the road.</p>
<p>If you wish to use another database, install the appropriate <a class="reference internal" href="../topics/install.html#database-installation"><em>database
bindings</em></a>, and change the following keys in the
<a class="reference internal" href="../ref/settings.html#std:setting-DATABASES"><tt class="xref std std-setting docutils literal"><span class="pre">DATABASES</span></tt></a> <tt class="docutils literal"><span class="pre">'default'</span></tt> item to match your database connection
settings:</p>
<ul class="simple">
<li><a class="reference internal" href="../ref/settings.html#std:setting-DATABASE-ENGINE"><tt class="xref std std-setting docutils literal"><span class="pre">ENGINE</span></tt></a> &#8211; Either
<tt class="docutils literal"><span class="pre">'django.db.backends.sqlite3'</span></tt>,
<tt class="docutils literal"><span class="pre">'django.db.backends.postgresql_psycopg2'</span></tt>,
<tt class="docutils literal"><span class="pre">'django.db.backends.mysql'</span></tt>, or
<tt class="docutils literal"><span class="pre">'django.db.backends.oracle'</span></tt>. Other backends are <a class="reference internal" href="../ref/databases.html#third-party-notes"><em>also available</em></a>.</li>
<li><a class="reference internal" href="../ref/settings.html#std:setting-NAME"><tt class="xref std std-setting docutils literal"><span class="pre">NAME</span></tt></a> &#8211; The name of your database. If you&#8217;re using SQLite, the
database will be a file on your computer; in that case, <a class="reference internal" href="../ref/settings.html#std:setting-NAME"><tt class="xref std std-setting docutils literal"><span class="pre">NAME</span></tt></a>
should be the full absolute path, including filename, of that file. The
default value, <tt class="docutils literal"><span class="pre">os.path.join(BASE_DIR,</span> <span class="pre">'db.sqlite3')</span></tt>, will store the file
in your project directory.</li>
</ul>
<p>If you are not using SQLite as your database, additional settings such as <a class="reference internal" href="../ref/settings.html#std:setting-USER"><tt class="xref std std-setting docutils literal"><span class="pre">USER</span></tt></a>, <a class="reference internal" href="../ref/settings.html#std:setting-PASSWORD"><tt class="xref std std-setting docutils literal"><span class="pre">PASSWORD</span></tt></a>, <a class="reference internal" href="../ref/settings.html#std:setting-HOST"><tt class="xref std std-setting docutils literal"><span class="pre">HOST</span></tt></a> must be added.
For more details, see the reference documentation for <a class="reference internal" href="../ref/settings.html#std:setting-DATABASES"><tt class="xref std std-setting docutils literal"><span class="pre">DATABASES</span></tt></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>If you&#8217;re using PostgreSQL or MySQL, make sure you&#8217;ve created a database by
this point. Do that with &#8220;<tt class="docutils literal"><span class="pre">CREATE</span> <span class="pre">DATABASE</span> <span class="pre">database_name;</span></tt>&#8221; within your
database&#8217;s interactive prompt.</p>
<p class="last">If you&#8217;re using SQLite, you don&#8217;t need to create anything beforehand - the
database file will be created automatically when it is needed.</p>
</div>
<p>While you&#8217;re editing <tt class="file docutils literal"><span class="pre">mysite/settings.py</span></tt>, set <a class="reference internal" href="../ref/settings.html#std:setting-TIME_ZONE"><tt class="xref std std-setting docutils literal"><span class="pre">TIME_ZONE</span></tt></a> to
your time zone.</p>
<p>Also, note the <a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> setting at the top of the file. That
holds the names of all Django applications that are activated in this Django
instance. Apps can be used in multiple projects, and you can package and
distribute them for use by others in their projects.</p>
<p>By default, <a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> contains the following apps, all of which
come with Django:</p>
<ul class="simple">
<li><a class="reference internal" href="../ref/contrib/admin/index.html#module-django.contrib.admin" title="django.contrib.admin: Django's admin site."><tt class="xref py py-mod docutils literal"><span class="pre">django.contrib.admin</span></tt></a> &#8211; The admin site. You&#8217;ll use it in <a class="reference internal" href="tutorial02.html"><em>part 2
of this tutorial</em></a>.</li>
<li><a class="reference internal" href="../topics/auth/index.html#module-django.contrib.auth" title="django.contrib.auth: Django's authentication framework."><tt class="xref py py-mod docutils literal"><span class="pre">django.contrib.auth</span></tt></a> &#8211; An authentication system.</li>
<li><a class="reference internal" href="../ref/contrib/contenttypes.html#module-django.contrib.contenttypes" title="django.contrib.contenttypes: Provides generic interface to installed models."><tt class="xref py py-mod docutils literal"><span class="pre">django.contrib.contenttypes</span></tt></a> &#8211; A framework for content types.</li>
<li><a class="reference internal" href="../topics/http/sessions.html#module-django.contrib.sessions" title="django.contrib.sessions: Provides session management for Django projects."><tt class="xref py py-mod docutils literal"><span class="pre">django.contrib.sessions</span></tt></a> &#8211; A session framework.</li>
<li><a class="reference internal" href="../ref/contrib/messages.html#module-django.contrib.messages" title="django.contrib.messages: Provides cookie- and session-based temporary message storage."><tt class="xref py py-mod docutils literal"><span class="pre">django.contrib.messages</span></tt></a> &#8211; A messaging framework.</li>
<li><a class="reference internal" href="../ref/contrib/staticfiles.html#module-django.contrib.staticfiles" title="django.contrib.staticfiles: An app for handling static files."><tt class="xref py py-mod docutils literal"><span class="pre">django.contrib.staticfiles</span></tt></a> &#8211; A framework for managing
static files.</li>
</ul>
<p>These applications are included by default as a convenience for the common case.</p>
<p>Some of these applications makes use of at least one database table, though,
so we need to create the tables in the database before we can use them. To do
that, run the following command:</p>
<div class="highlight-console"><div class="highlight"><pre><span class="gp">$</span> python manage.py migrate
</pre></div>
</div>
<p>The <a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">migrate</span></tt></a> command looks at the <a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> setting
and creates any necessary database tables according to the database settings
in your <tt class="file docutils literal"><span class="pre">mysite/settings.py</span></tt> file and the database migrations shipped
with the app (we&#8217;ll cover those later). You&#8217;ll see a message for each
migration it applies. If you&#8217;re interested, run the command-line client for your
database and type <tt class="docutils literal"><span class="pre">\dt</span></tt> (PostgreSQL), <tt class="docutils literal"><span class="pre">SHOW</span> <span class="pre">TABLES;</span></tt> (MySQL), or
<tt class="docutils literal"><span class="pre">.schema</span></tt> (SQLite) to display the tables Django created.</p>
<div class="admonition-for-the-minimalists admonition">
<p class="first admonition-title">For the minimalists</p>
<p class="last">Like we said above, the default applications are included for the common
case, but not everybody needs them. If you don&#8217;t need any or all of them,
feel free to comment-out or delete the appropriate line(s) from
<a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> before running <a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">migrate</span></tt></a>. The
<a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">migrate</span></tt></a> command will only run migrations for apps in
<a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a>.</p>
</div>
</div>
<div class="section" id="s-the-development-server">
<span id="the-development-server"></span><h3>The development server<a class="headerlink" href="#the-development-server" title="Permalink to this headline">¶</a></h3>
<p>Let&#8217;s verify your Django project works. Change into the outer <tt class="file docutils literal"><span class="pre">mysite</span></tt> directory, if
you haven&#8217;t already, and run the following commands:</p>
<div class="highlight-console"><div class="highlight"><pre><span class="gp">$</span> python manage.py runserver
</pre></div>
</div>
<p>You&#8217;ll see the following output on the command line:</p>
<pre class="literal-block">
Performing system checks...

0 errors found
April 02, 2015 - 15:50:53
Django version 1.7, using settings 'mysite.settings'
Starting development server at <a class="reference external" href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>
Quit the server with CONTROL-C.
</pre>
<p>You&#8217;ve started the Django development server, a lightweight Web server written
purely in Python. We&#8217;ve included this with Django so you can develop things
rapidly, without having to deal with configuring a production server &#8211; such as
Apache &#8211; until you&#8217;re ready for production.</p>
<p>Now&#8217;s a good time to note: <strong>don&#8217;t</strong> use this server in anything resembling a
production environment. It&#8217;s intended only for use while developing. (We&#8217;re in
the business of making Web frameworks, not Web servers.)</p>
<p>Now that the server&#8217;s running, visit <a class="reference external" href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a> with your Web
browser. You&#8217;ll see a &#8220;Welcome to Django&#8221; page, in pleasant, light-blue pastel.
It worked!</p>
<div class="admonition-changing-the-port admonition">
<p class="first admonition-title">Changing the port</p>
<p>By default, the <a class="reference internal" href="../ref/django-admin.html#django-admin-runserver"><tt class="xref std std-djadmin docutils literal"><span class="pre">runserver</span></tt></a> command starts the development server
on the internal IP at port 8000.</p>
<p>If you want to change the server&#8217;s port, pass
it as a command-line argument. For instance, this command starts the server
on port 8080:</p>
<div class="highlight-console"><div class="highlight"><pre><span class="gp">$</span> python manage.py runserver 8080
</pre></div>
</div>
<p>If you want to change the server&#8217;s IP, pass it along with the port. So to
listen on all public IPs (useful if you want to show off your work on other
computers), use:</p>
<div class="highlight-console"><div class="highlight"><pre><span class="gp">$</span> python manage.py runserver 0.0.0.0:8000
</pre></div>
</div>
<p class="last">Full docs for the development server can be found in the
<a class="reference internal" href="../ref/django-admin.html#django-admin-runserver"><tt class="xref std std-djadmin docutils literal"><span class="pre">runserver</span></tt></a> reference.</p>
</div>
<div class="admonition-automatic-reloading-of-djadmin-runserver admonition">
<p class="first admonition-title">Automatic reloading of <a class="reference internal" href="../ref/django-admin.html#django-admin-runserver"><tt class="xref std std-djadmin docutils literal"><span class="pre">runserver</span></tt></a></p>
<p class="last">The development server automatically reloads Python code for each request
as needed. You don&#8217;t need to restart the server for code changes to take
effect. However, some actions like adding files don&#8217;t trigger a restart,
so you&#8217;ll have to restart the server in these cases.</p>
</div>
</div>
</div>
<div class="section" id="s-creating-models">
<span id="s-id1"></span><span id="creating-models"></span><span id="id1"></span><h2>Creating models<a class="headerlink" href="#creating-models" title="Permalink to this headline">¶</a></h2>
<p>Now that your environment &#8211; a &#8220;project&#8221; &#8211; is set up, you&#8217;re set to start
doing work.</p>
<p>Each application you write in Django consists of a Python package that follows
a certain convention. Django comes with a utility that automatically generates
the basic directory structure of an app, so you can focus on writing code
rather than creating directories.</p>
<div class="admonition-projects-vs-apps admonition">
<p class="first admonition-title">Projects vs. apps</p>
<p class="last">What&#8217;s the difference between a project and an app? An app is a Web
application that does something &#8211; e.g., a Weblog system, a database of
public records or a simple poll app. A project is a collection of
configuration and apps for a particular Web site. A project can contain
multiple apps. An app can be in multiple projects.</p>
</div>
<p>Your apps can live anywhere on your <a class="reference external" href="http://docs.python.org/tutorial/modules.html#the-module-search-path">Python path</a>. In this tutorial, we&#8217;ll
create our poll app right next to your <tt class="file docutils literal"><span class="pre">manage.py</span></tt> file so that it can be
imported as its own top-level module, rather than a submodule of <tt class="docutils literal"><span class="pre">mysite</span></tt>.</p>
<p>To create your app, make sure you&#8217;re in the same directory as <tt class="file docutils literal"><span class="pre">manage.py</span></tt>
and type this command:</p>
<div class="highlight-console"><div class="highlight"><pre><span class="gp">$</span> python manage.py startapp polls
</pre></div>
</div>
<p>That&#8217;ll create a directory <tt class="file docutils literal"><span class="pre">polls</span></tt>, which is laid out like this:</p>
<div class="highlight-python"><div class="highlight"><pre>polls/
    __init__.py
    admin.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py
</pre></div>
</div>
<p>This directory structure will house the poll application.</p>
<p>The first step in writing a database Web app in Django is to define your models
&#8211; essentially, your database layout, with additional metadata.</p>
<div class="admonition-philosophy admonition">
<p class="first admonition-title">Philosophy</p>
<p>A model is the single, definitive source of data about your data. It contains
the essential fields and behaviors of the data you&#8217;re storing. Django follows
the <a class="reference internal" href="../misc/design-philosophies.html#dry"><em>DRY Principle</em></a>. The goal is to define your data model in one
place and automatically derive things from it.</p>
<p class="last">This includes the migrations - unlike in Ruby On Rails, for example, migrations
are entirely derived from your models file, and are essentially just a
history that Django can roll through to update your database schema to
match your current models.</p>
</div>
<p>In our simple poll app, we&#8217;ll create two models: <tt class="docutils literal"><span class="pre">Question</span></tt> and <tt class="docutils literal"><span class="pre">Choice</span></tt>.
A <tt class="docutils literal"><span class="pre">Question</span></tt> has a question and a publication date. A <tt class="docutils literal"><span class="pre">Choice</span></tt> has two fields:
the text of the choice and a vote tally. Each <tt class="docutils literal"><span class="pre">Choice</span></tt> is associated with a
<tt class="docutils literal"><span class="pre">Question</span></tt>.</p>
<p>These concepts are represented by simple Python classes. Edit the
<tt class="file docutils literal"><span class="pre">polls/models.py</span></tt> file so it looks like this:</p>
<div class="highlight-python"><div class="snippet-filename">polls/models.py</div>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>


<span class="k">class</span> <span class="nc">Question</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">question_text</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
    <span class="n">pub_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="s">&#39;date published&#39;</span><span class="p">)</span>


<span class="k">class</span> <span class="nc">Choice</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">question</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Question</span><span class="p">)</span>
    <span class="n">choice_text</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
    <span class="n">votes</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
<p>The code is straightforward. Each model is represented by a class that
subclasses <a class="reference internal" href="../ref/models/instances.html#django.db.models.Model" title="django.db.models.Model"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.Model</span></tt></a>. Each model has a number of class
variables, each of which represents a database field in the model.</p>
<p>Each field is represented by an instance of a <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a>
class &#8211; e.g., <a class="reference internal" href="../ref/models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><tt class="xref py py-class docutils literal"><span class="pre">CharField</span></tt></a> for character fields and
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateTimeField" title="django.db.models.DateTimeField"><tt class="xref py py-class docutils literal"><span class="pre">DateTimeField</span></tt></a> for datetimes. This tells Django what
type of data each field holds.</p>
<p>The name of each <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> instance (e.g. <tt class="docutils literal"><span class="pre">question_text</span></tt> or
<tt class="docutils literal"><span class="pre">pub_date</span></tt>) is the field&#8217;s name, in machine-friendly format. You&#8217;ll use this
value in your Python code, and your database will use it as the column name.</p>
<p>You can use an optional first positional argument to a
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> to designate a human-readable name. That&#8217;s used
in a couple of introspective parts of Django, and it doubles as documentation.
If this field isn&#8217;t provided, Django will use the machine-readable name. In this
example, we&#8217;ve only defined a human-readable name for <tt class="docutils literal"><span class="pre">Question.pub_date</span></tt>. For all
other fields in this model, the field&#8217;s machine-readable name will suffice as
its human-readable name.</p>
<p>Some <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> classes have required arguments.
<a class="reference internal" href="../ref/models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><tt class="xref py py-class docutils literal"><span class="pre">CharField</span></tt></a>, for example, requires that you give it a
<a class="reference internal" href="../ref/models/fields.html#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><tt class="xref py py-attr docutils literal"><span class="pre">max_length</span></tt></a>. That&#8217;s used not only in the
database schema, but in validation, as we&#8217;ll soon see.</p>
<p>A <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> can also have various optional arguments; in
this case, we&#8217;ve set the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.default" title="django.db.models.Field.default"><tt class="xref py py-attr docutils literal"><span class="pre">default</span></tt></a> value of
<tt class="docutils literal"><span class="pre">votes</span></tt> to 0.</p>
<p>Finally, note a relationship is defined, using
<a class="reference internal" href="../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>. That tells Django each <tt class="docutils literal"><span class="pre">Choice</span></tt> is related
to a single <tt class="docutils literal"><span class="pre">Question</span></tt>. Django supports all the common database relationships:
many-to-one, many-to-many and one-to-one.</p>
</div>
<div class="section" id="s-activating-models">
<span id="activating-models"></span><h2>Activating models<a class="headerlink" href="#activating-models" title="Permalink to this headline">¶</a></h2>
<p>That small bit of model code gives Django a lot of information. With it, Django
is able to:</p>
<ul class="simple">
<li>Create a database schema (<tt class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span></tt> statements) for this app.</li>
<li>Create a Python database-access API for accessing <tt class="docutils literal"><span class="pre">Question</span></tt> and <tt class="docutils literal"><span class="pre">Choice</span></tt> objects.</li>
</ul>
<p>But first we need to tell our project that the <tt class="docutils literal"><span class="pre">polls</span></tt> app is installed.</p>
<div class="admonition-philosophy admonition">
<p class="first admonition-title">Philosophy</p>
<p class="last">Django apps are &#8220;pluggable&#8221;: You can use an app in multiple projects, and
you can distribute apps, because they don&#8217;t have to be tied to a given
Django installation.</p>
</div>
<p>Edit the <tt class="file docutils literal"><span class="pre">mysite/settings.py</span></tt> file again, and change the
<a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><tt class="xref std std-setting docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> setting to include the string <tt class="docutils literal"><span class="pre">'polls'</span></tt>. So it&#8217;ll
look like this:</p>
<div class="highlight-python"><div class="snippet-filename">mysite/settings.py</div>
<div class="highlight"><pre><span class="n">INSTALLED_APPS</span> <span class="o">=</span> <span class="p">(</span>
    <span class="s">&#39;django.contrib.admin&#39;</span><span class="p">,</span>
    <span class="s">&#39;django.contrib.auth&#39;</span><span class="p">,</span>
    <span class="s">&#39;django.contrib.contenttypes&#39;</span><span class="p">,</span>
    <span class="s">&#39;django.contrib.sessions&#39;</span><span class="p">,</span>
    <span class="s">&#39;django.contrib.messages&#39;</span><span class="p">,</span>
    <span class="s">&#39;django.contrib.staticfiles&#39;</span><span class="p">,</span>
    <span class="s">&#39;polls&#39;</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
<p>Now Django knows to include the <tt class="docutils literal"><span class="pre">polls</span></tt> app. Let&#8217;s run another command:</p>
<div class="highlight-console"><div class="highlight"><pre><span class="gp">$</span> python manage.py makemigrations polls
</pre></div>
</div>
<p>You should see something similar to the following:</p>
<div class="highlight-text"><div class="highlight"><pre>Migrations for &#39;polls&#39;:
  0001_initial.py:
    - Create model Question
    - Create model Choice
    - Add field question to choice
</pre></div>
</div>
<p>By running <tt class="docutils literal"><span class="pre">makemigrations</span></tt>, you&#8217;re telling Django that you&#8217;ve made
some changes to your models (in this case, you&#8217;ve made new ones) and that
you&#8217;d like the changes to be stored as a <em>migration</em>.</p>
<p>Migrations are how Django stores changes to your models (and thus your
database schema) - they&#8217;re just files on disk. You can read the migration
for your new model if you like; it&#8217;s the file
<tt class="docutils literal"><span class="pre">polls/migrations/0001_initial.py</span></tt>. Don&#8217;t worry, you&#8217;re not expected to read
them every time Django makes one, but they&#8217;re designed to be human-editable
in case you want to manually tweak how Django changes things.</p>
<p>There&#8217;s a command that will run the migrations for you and manage your database
schema automatically - that&#8217;s called <a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">migrate</span></tt></a>, and we&#8217;ll come to it in a
moment - but first, let&#8217;s see what SQL that migration would run. The
<a class="reference internal" href="../ref/django-admin.html#django-admin-sqlmigrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">sqlmigrate</span></tt></a> command takes migration names and returns their SQL:</p>
<div class="highlight-console"><div class="highlight"><pre><span class="gp">$</span> python manage.py sqlmigrate polls 0001
</pre></div>
</div>
<p>You should see something similar to the following (we&#8217;ve reformatted it for
readability):</p>
<div class="highlight-sql"><div class="highlight"><pre><span class="k">BEGIN</span><span class="p">;</span>
<span class="k">CREATE</span> <span class="k">TABLE</span> <span class="ss">&quot;polls_choice&quot;</span> <span class="p">(</span>
    <span class="ss">&quot;id&quot;</span> <span class="nb">serial</span> <span class="k">NOT</span> <span class="k">NULL</span> <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">,</span>
    <span class="ss">&quot;choice_text&quot;</span> <span class="nb">varchar</span><span class="p">(</span><span class="mi">200</span><span class="p">)</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="ss">&quot;votes&quot;</span> <span class="nb">integer</span> <span class="k">NOT</span> <span class="k">NULL</span>
<span class="p">);</span>
<span class="k">CREATE</span> <span class="k">TABLE</span> <span class="ss">&quot;polls_question&quot;</span> <span class="p">(</span>
    <span class="ss">&quot;id&quot;</span> <span class="nb">serial</span> <span class="k">NOT</span> <span class="k">NULL</span> <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">,</span>
    <span class="ss">&quot;question_text&quot;</span> <span class="nb">varchar</span><span class="p">(</span><span class="mi">200</span><span class="p">)</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="ss">&quot;pub_date&quot;</span> <span class="k">timestamp</span> <span class="k">with</span> <span class="n">time</span> <span class="k">zone</span> <span class="k">NOT</span> <span class="k">NULL</span>
<span class="p">);</span>
<span class="k">ALTER</span> <span class="k">TABLE</span> <span class="ss">&quot;polls_choice&quot;</span> <span class="k">ADD</span> <span class="k">COLUMN</span> <span class="ss">&quot;question_id&quot;</span> <span class="nb">integer</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">;</span>
<span class="k">ALTER</span> <span class="k">TABLE</span> <span class="ss">&quot;polls_choice&quot;</span> <span class="k">ALTER</span> <span class="k">COLUMN</span> <span class="ss">&quot;question_id&quot;</span> <span class="k">DROP</span> <span class="k">DEFAULT</span><span class="p">;</span>
<span class="k">CREATE</span> <span class="k">INDEX</span> <span class="ss">&quot;polls_choice_7aa0f6ee&quot;</span> <span class="k">ON</span> <span class="ss">&quot;polls_choice&quot;</span> <span class="p">(</span><span class="ss">&quot;question_id&quot;</span><span class="p">);</span>
<span class="k">ALTER</span> <span class="k">TABLE</span> <span class="ss">&quot;polls_choice&quot;</span>
  <span class="k">ADD</span> <span class="k">CONSTRAINT</span> <span class="ss">&quot;polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id&quot;</span>
    <span class="k">FOREIGN</span> <span class="k">KEY</span> <span class="p">(</span><span class="ss">&quot;question_id&quot;</span><span class="p">)</span>
    <span class="k">REFERENCES</span> <span class="ss">&quot;polls_question&quot;</span> <span class="p">(</span><span class="ss">&quot;id&quot;</span><span class="p">)</span>
    <span class="k">DEFERRABLE</span> <span class="k">INITIALLY</span> <span class="k">DEFERRED</span><span class="p">;</span>

<span class="k">COMMIT</span><span class="p">;</span>
</pre></div>
</div>
<p>Note the following:</p>
<ul class="simple">
<li>The exact output will vary depending on the database you are using. The
example above is generated for PostgreSQL.</li>
<li>Table names are automatically generated by combining the name of the app
(<tt class="docutils literal"><span class="pre">polls</span></tt>) and the lowercase name of the model &#8211; <tt class="docutils literal"><span class="pre">question</span></tt> and
<tt class="docutils literal"><span class="pre">choice</span></tt>. (You can override this behavior.)</li>
<li>Primary keys (IDs) are added automatically. (You can override this, too.)</li>
<li>By convention, Django appends <tt class="docutils literal"><span class="pre">&quot;_id&quot;</span></tt> to the foreign key field name.
(Yes, you can override this, as well.)</li>
<li>The foreign key relationship is made explicit by a <tt class="docutils literal"><span class="pre">FOREIGN</span> <span class="pre">KEY</span></tt>
constraint. Don&#8217;t worry about the <tt class="docutils literal"><span class="pre">DEFERRABLE</span></tt> parts; that&#8217;s just telling
PostgreSQL to not enforce the foreign key until the end of the transaction.</li>
<li>It&#8217;s tailored to the database you&#8217;re using, so database-specific field types
such as <tt class="docutils literal"><span class="pre">auto_increment</span></tt> (MySQL), <tt class="docutils literal"><span class="pre">serial</span></tt> (PostgreSQL), or <tt class="docutils literal"><span class="pre">integer</span>
<span class="pre">primary</span> <span class="pre">key</span> <span class="pre">autoincrement</span></tt> (SQLite) are handled for you automatically. Same
goes for quoting of field names &#8211; e.g., using double quotes or single
quotes.</li>
<li>The <a class="reference internal" href="../ref/django-admin.html#django-admin-sqlmigrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">sqlmigrate</span></tt></a> command doesn&#8217;t actually run the migration on your
database - it just prints it to the screen so that you can see what SQL
Django thinks is required. It&#8217;s useful for checking what Django is going to
do or if you have database administrators who require SQL scripts for
changes.</li>
</ul>
<p>If you&#8217;re interested, you can also run
<a class="reference internal" href="../ref/django-admin.html#django-admin-check"><tt class="xref std std-djadmin docutils literal"><span class="pre">python</span> <span class="pre">manage.py</span> <span class="pre">check</span></tt></a>; this checks for any problems in
your project without making migrations or touching the database.</p>
<p>Now, run <a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">migrate</span></tt></a> again to create those model tables in your database:</p>
<div class="highlight-console"><div class="highlight"><pre><span class="gp">$</span> python manage.py migrate
<span class="go">Operations to perform:</span>
<span class="go">  Apply all migrations: admin, contenttypes, polls, auth, sessions</span>
<span class="go">Running migrations:</span>
<span class="go">  Applying &lt;migration name&gt;... OK</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">migrate</span></tt></a> command takes all the migrations that haven&#8217;t been
applied (Django tracks which ones are applied using a special table in your
database called <tt class="docutils literal"><span class="pre">django_migrations</span></tt>) and runs them against your database -
essentially, synchronizing the changes you made to your models with the schema
in the database.</p>
<p>Migrations are very powerful and let you change your models over time, as you
develop your project, without the need to delete your database or tables and
make new ones - it specializes in upgrading your database live, without
losing data. We&#8217;ll cover them in more depth in a later part of the tutorial,
but for now, remember the three-step guide to making model changes:</p>
<ul class="simple">
<li>Change your models (in <tt class="docutils literal"><span class="pre">models.py</span></tt>).</li>
<li>Run <a class="reference internal" href="../ref/django-admin.html#django-admin-makemigrations"><tt class="xref std std-djadmin docutils literal"><span class="pre">python</span> <span class="pre">manage.py</span> <span class="pre">makemigrations</span></tt></a> to create
migrations for those changes</li>
<li>Run <a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">python</span> <span class="pre">manage.py</span> <span class="pre">migrate</span></tt></a> to apply those changes to
the database.</li>
</ul>
<p>The reason there&#8217;s separate commands to make and apply migrations is because
you&#8217;ll commit migrations to your version control system and ship them with
your app; they not only make your development easier, they&#8217;re also useable by
other developers and in production.</p>
<p>Read the <a class="reference internal" href="../ref/django-admin.html"><em>django-admin.py documentation</em></a> for full
information on what the <tt class="docutils literal"><span class="pre">manage.py</span></tt> utility can do.</p>
</div>
<div class="section" id="s-playing-with-the-api">
<span id="playing-with-the-api"></span><h2>Playing with the API<a class="headerlink" href="#playing-with-the-api" title="Permalink to this headline">¶</a></h2>
<p>Now, let&#8217;s hop into the interactive Python shell and play around with the free
API Django gives you. To invoke the Python shell, use this command:</p>
<div class="highlight-console"><div class="highlight"><pre><span class="gp">$</span> python manage.py shell
</pre></div>
</div>
<p>We&#8217;re using this instead of simply typing &#8220;python&#8221;, because <tt class="file docutils literal"><span class="pre">manage.py</span></tt>
sets the <tt class="docutils literal"><span class="pre">DJANGO_SETTINGS_MODULE</span></tt> environment variable, which gives Django
the Python import path to your <tt class="file docutils literal"><span class="pre">mysite/settings.py</span></tt> file.</p>
<div class="admonition-bypassing-manage-py admonition">
<p class="first admonition-title">Bypassing manage.py</p>
<p>If you&#8217;d rather not use <tt class="file docutils literal"><span class="pre">manage.py</span></tt>, no problem. Just set the
<span class="target" id="index-0"></span><a class="reference internal" href="../topics/settings.html#envvar-DJANGO_SETTINGS_MODULE"><tt class="xref std std-envvar docutils literal"><span class="pre">DJANGO_SETTINGS_MODULE</span></tt></a> environment variable to
<tt class="docutils literal"><span class="pre">mysite.settings</span></tt>, start a plain Python shell, and set up Django:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">django</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">django</span><span class="o">.</span><span class="n">setup</span><span class="p">()</span>
</pre></div>
</div>
<p>If this raises an <a class="reference external" href="http://docs.python.org/3/library/exceptions.html#AttributeError" title="(in Python v3.4)"><tt class="xref py py-exc docutils literal"><span class="pre">AttributeError</span></tt></a>, you&#8217;re probably using
a version of Django that doesn&#8217;t match this tutorial version. You&#8217;ll want
to either switch to the older tutorial or the newer Django version.</p>
<p>You must run <tt class="docutils literal"><span class="pre">python</span></tt> from the same directory <tt class="file docutils literal"><span class="pre">manage.py</span></tt> is in,
or ensure that directory is on the Python path, so that <tt class="docutils literal"><span class="pre">import</span> <span class="pre">mysite</span></tt>
works.</p>
<p class="last">For more information on all of this, see the <a class="reference internal" href="../ref/django-admin.html"><em>django-admin.py
documentation</em></a>.</p>
</div>
<p>Once you&#8217;re in the shell, explore the <a class="reference internal" href="../topics/db/queries.html"><em>database API</em></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">polls.models</span> <span class="kn">import</span> <span class="n">Question</span><span class="p">,</span> <span class="n">Choice</span>   <span class="c"># Import the model classes we just wrote.</span>

<span class="go"># No questions are in the system yet.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>

<span class="go"># Create a new Question.</span>
<span class="go"># Support for time zones is enabled in the default settings file, so</span>
<span class="go"># Django expects a datetime with tzinfo for pub_date. Use timezone.now()</span>
<span class="go"># instead of datetime.datetime.now() and it will do the right thing.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Question</span><span class="p">(</span><span class="n">question_text</span><span class="o">=</span><span class="s">&quot;What&#39;s new?&quot;</span><span class="p">,</span> <span class="n">pub_date</span><span class="o">=</span><span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>

<span class="go"># Save the object into the database. You have to call save() explicitly.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>

<span class="go"># Now it has an ID. Note that this might say &quot;1L&quot; instead of &quot;1&quot;, depending</span>
<span class="go"># on which database you&#39;re using. That&#39;s no biggie; it just means your</span>
<span class="go"># database backend prefers to return integers as Python long integer</span>
<span class="go"># objects.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">id</span>
<span class="go">1</span>

<span class="go"># Access model field values via Python attributes.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">question_text</span>
<span class="go">&quot;What&#39;s new?&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">pub_date</span>
<span class="go">datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=&lt;UTC&gt;)</span>

<span class="go"># Change values by changing the attributes, then calling save().</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">question_text</span> <span class="o">=</span> <span class="s">&quot;What&#39;s up?&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>

<span class="go"># objects.all() displays all the questions in the database.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Question: Question object&gt;]</span>
</pre></div>
</div>
<p>Wait a minute. <tt class="docutils literal"><span class="pre">&lt;Question:</span> <span class="pre">Question</span> <span class="pre">object&gt;</span></tt> is, utterly, an unhelpful representation
of this object. Let&#8217;s fix that by editing the <tt class="docutils literal"><span class="pre">Question</span></tt> model (in the
<tt class="docutils literal"><span class="pre">polls/models.py</span></tt> file) and adding a
<a class="reference internal" href="../ref/models/instances.html#django.db.models.Model.__str__" title="django.db.models.Model.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt></a> method to both <tt class="docutils literal"><span class="pre">Question</span></tt> and
<tt class="docutils literal"><span class="pre">Choice</span></tt>:</p>
<div class="highlight-python"><div class="snippet-filename">polls/models.py</div>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Question</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>              <span class="c"># __unicode__ on Python 2</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">question_text</span>

<span class="k">class</span> <span class="nc">Choice</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>              <span class="c"># __unicode__ on Python 2</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">choice_text</span>
</pre></div>
</div>
<p>It&#8217;s important to add <a class="reference internal" href="../ref/models/instances.html#django.db.models.Model.__str__" title="django.db.models.Model.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt></a> methods to your
models, not only for your own convenience when dealing with the interactive
prompt, but also because objects&#8217; representations are used throughout Django&#8217;s
automatically-generated admin.</p>
<div class="admonition-str-or-unicode admonition">
<p class="first admonition-title"><tt class="docutils literal"><span class="pre">__str__</span></tt> or <tt class="docutils literal"><span class="pre">__unicode__</span></tt>?</p>
<p>On Python 3, it&#8217;s easy, just use
<a class="reference internal" href="../ref/models/instances.html#django.db.models.Model.__str__" title="django.db.models.Model.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt></a>.</p>
<p>On Python 2, you should define <a class="reference internal" href="../ref/models/instances.html#django.db.models.Model.__unicode__" title="django.db.models.Model.__unicode__"><tt class="xref py py-meth docutils literal"><span class="pre">__unicode__()</span></tt></a>
methods returning <tt class="docutils literal"><span class="pre">unicode</span></tt> values instead. Django models have a default
<a class="reference internal" href="../ref/models/instances.html#django.db.models.Model.__str__" title="django.db.models.Model.__str__"><tt class="xref py py-meth docutils literal"><span class="pre">__str__()</span></tt></a> method that calls
<a class="reference internal" href="../ref/models/instances.html#django.db.models.Model.__unicode__" title="django.db.models.Model.__unicode__"><tt class="xref py py-meth docutils literal"><span class="pre">__unicode__()</span></tt></a> and converts the result to a
UTF-8 bytestring. This means that <tt class="docutils literal"><span class="pre">unicode(p)</span></tt> will return a Unicode
string, and <tt class="docutils literal"><span class="pre">str(p)</span></tt> will return a bytestring, with characters encoded
as UTF-8. Python does the opposite: <tt class="docutils literal"><span class="pre">object</span></tt> has a <tt class="docutils literal"><span class="pre">__unicode__</span></tt>
method that calls <tt class="docutils literal"><span class="pre">__str__</span></tt> and interprets the result as an ASCII
bytestring. This difference can create confusion.</p>
<p class="last">If all of this is gibberish to you, just use Python 3.</p>
</div>
<p>Note these are normal Python methods. Let&#8217;s add a custom method, just for
demonstration:</p>
<div class="highlight-python"><div class="snippet-filename">polls/models.py</div>
<div class="highlight"><pre><span class="kn">import</span> <span class="nn">datetime</span>

<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>


<span class="k">class</span> <span class="nc">Question</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="k">def</span> <span class="nf">was_published_recently</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">pub_date</span> <span class="o">&gt;=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">()</span> <span class="o">-</span> <span class="n">datetime</span><span class="o">.</span><span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>Note the addition of <tt class="docutils literal"><span class="pre">import</span> <span class="pre">datetime</span></tt> and <tt class="docutils literal"><span class="pre">from</span> <span class="pre">django.utils</span> <span class="pre">import</span>
<span class="pre">timezone</span></tt>, to reference Python&#8217;s standard <a class="reference external" href="http://docs.python.org/3/library/datetime.html#module-datetime" title="(in Python v3.4)"><tt class="xref py py-mod docutils literal"><span class="pre">datetime</span></tt></a> module and Django&#8217;s
time-zone-related utilities in <a class="reference internal" href="../ref/utils.html#module-django.utils.timezone" title="django.utils.timezone: Timezone support."><tt class="xref py py-mod docutils literal"><span class="pre">django.utils.timezone</span></tt></a>, respectively. If
you aren&#8217;t familiar with time zone handling in Python, you can learn more in
the <a class="reference internal" href="../topics/i18n/timezones.html"><em>time zone support docs</em></a>.</p>
<p>Save these changes and start a new Python interactive shell by running
<tt class="docutils literal"><span class="pre">python</span> <span class="pre">manage.py</span> <span class="pre">shell</span></tt> again:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">polls.models</span> <span class="kn">import</span> <span class="n">Question</span><span class="p">,</span> <span class="n">Choice</span>

<span class="go"># Make sure our __str__() addition worked.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Question: What&#39;s up?&gt;]</span>

<span class="go"># Django provides a rich database lookup API that&#39;s entirely driven by</span>
<span class="go"># keyword arguments.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[&lt;Question: What&#39;s up?&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">question_text__startswith</span><span class="o">=</span><span class="s">&#39;What&#39;</span><span class="p">)</span>
<span class="go">[&lt;Question: What&#39;s up?&gt;]</span>

<span class="go"># Get the question that was published this year.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.utils</span> <span class="kn">import</span> <span class="n">timezone</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">current_year</span> <span class="o">=</span> <span class="n">timezone</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">.</span><span class="n">year</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="n">current_year</span><span class="p">)</span>
<span class="go">&lt;Question: What&#39;s up?&gt;</span>

<span class="go"># Request an ID that doesn&#39;t exist, this will raise an exception.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">...</span>
<span class="gr">DoesNotExist</span>: <span class="n">Question matching query does not exist.</span>

<span class="go"># Lookup by a primary key is the most common case, so Django provides a</span>
<span class="go"># shortcut for primary-key exact lookups.</span>
<span class="go"># The following is identical to Question.objects.get(id=1).</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&lt;Question: What&#39;s up?&gt;</span>

<span class="go"># Make sure our custom method worked.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">was_published_recently</span><span class="p">()</span>
<span class="go">True</span>

<span class="go"># Give the Question a couple of Choices. The create call constructs a new</span>
<span class="go"># Choice object, does the INSERT statement, adds the choice to the set</span>
<span class="go"># of available choices and returns the new Choice object. Django creates</span>
<span class="go"># a set to hold the &quot;other side&quot; of a ForeignKey relation</span>
<span class="go"># (e.g. a question&#39;s choice) which can be accessed via the API.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Question</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

<span class="go"># Display any choices from the related object set -- none so far.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[]</span>

<span class="go"># Create three choices.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice_text</span><span class="o">=</span><span class="s">&#39;Not much&#39;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="go">&lt;Choice: Not much&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice_text</span><span class="o">=</span><span class="s">&#39;The sky&#39;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="go">&lt;Choice: The sky&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">choice_text</span><span class="o">=</span><span class="s">&#39;Just hacking again&#39;</span><span class="p">,</span> <span class="n">votes</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>

<span class="go"># Choice objects have API access to their related Question objects.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">question</span>
<span class="go">&lt;Question: What&#39;s up?&gt;</span>

<span class="go"># And vice versa: Question objects get access to Choice objects.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">[&lt;Choice: Not much&gt;, &lt;Choice: The sky&gt;, &lt;Choice: Just hacking again&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
<span class="go">3</span>

<span class="go"># The API automatically follows relationships as far as you need.</span>
<span class="go"># Use double underscores to separate relationships.</span>
<span class="go"># This works as many levels deep as you want; there&#39;s no limit.</span>
<span class="go"># Find all Choices for any question whose pub_date is in this year</span>
<span class="go"># (reusing the &#39;current_year&#39; variable we created above).</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Choice</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">question__pub_date__year</span><span class="o">=</span><span class="n">current_year</span><span class="p">)</span>
<span class="go">[&lt;Choice: Not much&gt;, &lt;Choice: The sky&gt;, &lt;Choice: Just hacking again&gt;]</span>

<span class="go"># Let&#39;s delete one of the choices. Use delete() for that.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">choice_text__startswith</span><span class="o">=</span><span class="s">&#39;Just hacking&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
</pre></div>
</div>
<p>For more information on model relations, see <a class="reference internal" href="../ref/models/relations.html"><em>Accessing related objects</em></a>. For more on how to use double underscores to perform
field lookups via the API, see <a class="reference internal" href="../topics/db/queries.html#field-lookups-intro"><em>Field lookups</em></a>. For
full details on the database API, see our <a class="reference internal" href="../topics/db/queries.html"><em>Database API reference</em></a>.</p>
<p>When you&#8217;re comfortable with the API, read <a class="reference internal" href="tutorial02.html"><em>part 2 of this tutorial</em></a> to get Django&#8217;s automatic admin working.</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Writing your first Django app, part 1</a><ul>
<li><a class="reference internal" href="#creating-a-project">Creating a project</a><ul>
<li><a class="reference internal" href="#database-setup">Database setup</a></li>
<li><a class="reference internal" href="#the-development-server">The development server</a></li>
</ul>
</li>
<li><a class="reference internal" href="#creating-models">Creating models</a></li>
<li><a class="reference internal" href="#activating-models">Activating models</a></li>
<li><a class="reference internal" href="#playing-with-the-api">Playing with the API</a></li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="install.html">Quick install guide</a></li>
    
    
      <li>Next: <a href="tutorial02.html">Writing your first Django app, part 2</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="index.html">Getting started</a>
        
        <ul><li>Writing your first Django app, part 1</li></ul>
        </li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../_sources/intro/tutorial01.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="install.html" title="Quick install guide">previous</a>
     |
    <a href="index.html" title="Getting started" accesskey="U">up</a>
   |
    <a href="tutorial02.html" title="Writing your first Django app, part 2">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>